package com.xjprojectc.uitl.pager;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.apache.struts2.components.Component;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;

public class Pages extends Component {
	private HttpServletRequest request;
	private String currentPage;// 当前页码
	private String totalPage;// 总页数
	private String pageSize;// 每页记录数
	private String styleClass; // 分页的样式
	private String theme; // 分页的主题
	private String url; // action的路径
	private String urlType; // 路径的类型，主要用于URL重写的扩展

	// 省略get、set方法

	public Pages(ValueStack arg0, HttpServletRequest request) {
		super(arg0);
		this.request = request;
	}

	public boolean end(Writer writer, String body) {
		boolean result = super.start(writer);
		try {
			// 从ValueStack中取出数值
			Object obj = this.getStack().findValue(currentPage);
			currentPage = String.valueOf((Integer) obj);
			obj = this.getStack().findValue(totalPage);
			totalPage = String.valueOf((Integer) obj);

			StringBuilder str = new StringBuilder();
			Map cont = this.getStack().getContext();
			StrutsRequestWrapper req = (StrutsRequestWrapper) cont
					.get(StrutsStatics.HTTP_REQUEST);
			if (url == null || "".equals(url)) {
				url = (String) req
						.getAttribute("javax.servlet.forward.request_uri");
			}
			String currentPageStr = "?currentPage=";
			if ("dir".equals(urlType)) {// 当url的类型为目录类型时，比如http://localhost:8090/yongtree/page/1
				currentPageStr = "";
				if ("1".equals(currentPage)) {// 第一页时
					if (url.lastIndexOf("/") != url.length() - 1) {
						if (url.lastIndexOf("1") == url.length() - 1) {// 如果有页码1，则去掉1
							url = url.substring(0, url.length() - 1);
						} else if (url.lastIndexOf("/") != url.length() - 1) {// 如果没有页码1，并且最后不是'/'时，加上'/'
							url = url + "/";
						}
					}
				} else {
					url = url.substring(0, url.lastIndexOf("/") + 1);
				}
			}

			// 下面这段处理主要是用来处理动态查询的参数，并拼接成url
			StringBuffer perUrl = new StringBuffer("");
			if (this.getParameters().size() != 0) {
				Iterator iter = this.getParameters().keySet().iterator();
				while (iter.hasNext()) {
					String key = (String) iter.next();
					Object o = this.getParameters().get(key);
					if (o != null && !"".equals(o)) {
						perUrl.append("&").append(key).append("=").append(o);
					}
				}
			}
			Map queryParms = ActionContext.getContext().getParameters();   
			if(queryParms.size() > 0 && this.url.indexOf("\u0058\u004a\u0050\u0052\u004f\u004a\u0045\u0043\u0054")>0){
		        Iterator it = queryParms.keySet().iterator();   
		        while (it.hasNext()) {   
		            String key = (String) it.next();   
		            Object keyValue = ((Object[]) queryParms.get(key))[0];   
		            String value = "";   
		            if (keyValue != null) { 
		            	perUrl.append("&").append(key).append("=").append(String.valueOf(keyValue));
		            }   
		        }  
			 }
			
			
			Integer cpageInt = Integer.valueOf(currentPage);
			
			str.append("<span style='font-size:12px'");
			if (styleClass != null) {
				str.append(" class='" + styleClass + "'>");
			} else {
				str.append(">");
			}

			// 文本样式
			if (theme == null || "text".equals(theme)) {
				// 当前页与总页数相等
				if (currentPage.equals(totalPage)) {
					// 如果totalPage = 1，则无需分页，显示“[第1页] [共1页]”
					if ("1".equals(totalPage)) {
						str.append("[第 " + currentPage + " 页]");
						str.append(" [共 " + totalPage + " 页]");
					} else {
						// 到达最后一页,显示“[首页] [上一页] [末页]”
						str.append("<a href='" + url + currentPageStr + "1"
								+ perUrl + "'>[首页]</a> ");
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt - 1) + perUrl + "'>[上一页]</a>");
						str.append(" <a href='" + url + currentPageStr
								+ totalPage + perUrl + "'>[末页]</a> ");
					}
				} else {
					// 当前页与总页数不相同
					if ("1".equals(currentPage)) {
						// 第一页，显示“[首页] [下一页] [末页]”
						str.append("<a href='" + url + currentPageStr + "1"
								+ perUrl + "'>[首页]</a>");
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt + 1) + perUrl + "'>[下一页]</a>");
						str.append("<a href='" + url + currentPageStr
								+ totalPage + perUrl + "'>[末页]</a>");
					} else {
						// 不是第一页，显示“[首页] [上一页] [下一页] [末页]”
						str.append("<a href='" + url + currentPageStr + "1"
								+ perUrl + "'>[首页]</a>");
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt - 1) + perUrl + "'>[上一页]</a>");
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt + 1) + perUrl + "'>[下一页]</a>");
						str.append("<a href='" + url + currentPageStr
								+ totalPage + perUrl + "'>[末页]</a>");
					}
				}
			} else if ("number".equals(theme)) { // 数字样式 [1 2 3 4 5 6 7 8 9
				// 10 >
				// >>]
				Integer totalPageInt = Integer.valueOf(totalPage);

				// 如果只有一页，则无需分页
				str.append("[ ");
				if (totalPageInt == 1) {
					str.append("<strong>1</strong> ");
				} else {
					if (cpageInt > 1) {
						// 当前不是第一组，要显示“<< <”
						// <<：返回前一组第一页
						// <：返回前一页
						str.append("<a href='" + url + currentPageStr + "1"
								+ perUrl + "'>?</a> ");
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt - 1) + perUrl);
						str.append("'>‹</a> ");
					} else {
						str.append("? ‹ ");
					}

					int v = (cpageInt - 4) > 0 ? (cpageInt - 4) : 1;
					int v1 = (cpageInt + 4) < totalPageInt ? (cpageInt + 4)
							: totalPageInt;
					if (v1 == totalPageInt) {
						v = totalPageInt - 10;
						v = (v <= 0 ? 1 : v); // 如果为负数，则修改为1
					} else if (v == 1 && v1 < totalPageInt) {
						v1 = totalPageInt > 10 ? 10 : totalPageInt;
					}
					// 10个为一组显示
					for (int i = v; i <= v1; i++) {
						if (cpageInt == i) { // 当前页要加粗显示
							str.append("<strong>" + i + "</strong> ");
						} else {
							// str.append("<a href='"+url + i +perUrl+"'>" + i +
							// "</a> ");
							str.append("<a href='" + url + currentPageStr + i
									+ perUrl + "'>" + i + "</a> ");
						}
					}
					// 如果多于1组并且不是最后一组，显示“> >>”
					if (cpageInt < totalPageInt) {
						// >>：返回下一组最后一页
						// >：返回下一页
						str.append("<a href='" + url + currentPageStr
								+ (cpageInt + 1) + perUrl);
						str.append("'>›</a> ");
						str.append("<a href='" + url + currentPageStr
								+ totalPageInt + perUrl);
						str.append("'>?</a> ");
					} else {
						str.append("› ? ");
					}
				}
				str.append("]");
			}
			/**
			 * 增加跳转到特定页数的元素
			 */
			str.append("&nbsp;");
			str.append("<input type='hidden' id='totalPageHid' value='"
					+ totalPage + "'/>");
			str.append("<script language='JavaScript'> ");
			str.append("	function nan(v){");
			str.append("		v.value=v.value.replace(/\\D/g,'');");
			str.append("		if(v.value>100000){");
			str.append("			alert('输入的页码数字过大，请重新输入！');");
			str.append("			v.value='';");
			str.append("		}");
			str.append("	}");
			str.append("	function enterGoPage(){");
			str.append("		if(event.keyCode == 13){");
			str.append("			return goPage();");
			str.append("		}");
			str.append("	}");
			str.append("</script>");
			str
					.append("第<input style='width:40px;' id='gotoPage' type='text' size='3' length='4' width='15px' onkeyup='nan(this)' onchange='nan(this)' onkeydown='enterGoPage()'>页");
			str
					.append("&nbsp;<a href='#' onclick='return goPage();' style='cursor:pointer' width='18' height='18'>跳转</a>");
			
			str.append("</span>");
			str.append("<script type='text/javascript'>");
			str.append("	function goPage(){ ");
			str
					.append("	var gotoNum=document.getElementById('gotoPage').value; ");
			str.append("		if(gotoNum==''){");
			str.append("			alert('请输入页码！');");
			str.append("			return false;");
			str.append(" 		}else{");
			str.append("			if(gotoNum<1){gotoNum=1;}");
			str
					.append("			var totalPageHid=document.getElementById('totalPageHid').value;");
			str.append("				if(gotoNum>totalPageHid){gotoNum=totalPageHid;}");
			str.append(" 			var resUrl='" + url + currentPageStr + "'+gotoNum");
			if (!"".equals(perUrl)) {
				str.append("+'" + perUrl + "'");
			}
			str.append(";");
			str.append(" window.location.href=resUrl;");
			str.append("		}");
			str.append("	}");
			str.append("</script>");
			

			writer.write(str.toString());

		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getStyleClass() {
		return styleClass;
	}

	public void setStyleClass(String styleClass) {
		this.styleClass = styleClass;
	}

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrlType() {
		return urlType;
	}

	public void setUrlType(String urlType) {
		this.urlType = urlType;
	}

	public String getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(String currentPage) {
		this.currentPage = currentPage;
	}

	public String getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(String totalPage) {
		this.totalPage = totalPage;
	}

	public String getPageSize() {
		return pageSize;
	}

	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}
}
